'use strict';
const ObjectId = require('mongoose').Types.ObjectId;


module.exports = app => {
  class AppController extends app.Controller {
    * find() {

    }

    * addPermit() {
      const appId = this.ctx.request.body.id;
      const permitId = this.ctx.request.body.permitId;
      try {
        // use $addToSet to avoid duplication
        const appDoc = yield app.model.app.findByIdAndUpdate(appId, { $addToSet: { 'attributes.permits': permitId } });
        this.ctx.body = yield appDoc.populate('attributes.permits').execPopulate();
      } catch (e) {
        console.log(e);
        this.ctx.body = {
          error: e,
        };
      }
    }

    * listPermit() {
      const id = this.ctx.params.id;
      const appDoc = yield app.model.app.findById(id);
      try {
        const populatedDoc = yield appDoc.populate('attributes.permits').execPopulate();
        this.ctx.body = {
          count: populatedDoc.attributes.permits.length,
          permits: populatedDoc.attributes.permits,
        };
      } catch (e) {
        console.log(e);
        this.ctx.body = {
          error: e,
        };
      }
    }

    /**
     * get app by id
     */
    * show() {
      const id = this.ctx.params.id;
      const results = yield app.model.app.findById(id);
      this.ctx.body = results;
    }

    /**
     * create new app
     */
    * create() {
      const name = this.ctx.request.body.name;
      if (yield app.model.app.findOne({ name }).exec()) {
        this.ctx.body = {
          isSuccess: false,
          msg: '应用名称已被使用',
        };
      } else {
        const newApp = new app.model.app({
          name,
        });
        const results = yield newApp.save();
        this.ctx.body = results;
      }
    }

    /**
     * delete app by id
     */
    * destroy() {
      const id = this.ctx.params.id;
      const results = yield app.model.app.remove({ _id: ObjectId(id) });
      this.ctx.body = results;
    }
  }
  return AppController;
};

